import { useCallback, useRef, useState } from 'react';
import { message, Modal, Space, Spin } from 'antd';

import { numberWithThousands, processConfidenceNumber } from '@/utils/number';

import { DEFAULT_CONFIDENCE } from './constants';
import CrowdCountAdjust from './CrowdCountAdjust';

const DEFAULT_DATA = {
  coverage: 0,
  p_date: '',
};
const initExpandTag = {
  groupId: '',
  groupName: '',
  description: '',
  customType: '',
  coverage: '',
  crowdId: '',
  minCoverage: '',
  value: {},
};

const CrowdExpandAdjustModal = ({
  groupTagInfo = {},
  clearGroupTagInfo,
  selectGroupTag,
  dimId,
  visible,
  onClose,
  propsGroupTagInfo = {},
}) => {
  const {
    groupId,
    groupName,
    description,
    coverage,
    crowdId,
    minCoverage,
    value,
  } = groupTagInfo ?? propsGroupTagInfo ?? initExpandTag;
  const contentRef = useRef();
  const [data, setData] = useState(DEFAULT_DATA);
  const [confidence, setConfidence] = useState(DEFAULT_CONFIDENCE);
  const [loading, setLoading] = useState(false);

  const onRequest = useCallback(() => {
    setLoading(true);
  }, []);
  const onSuccess = useCallback(
    ({ coverage = 0, p_date = '' } = DEFAULT_DATA) => {
      setLoading(false);
      setData({ coverage, p_date });
    },
    [],
  );

  const handleClearInfo = () => {
    onClose();
    contentRef.current?.form.resetFields();
    clearGroupTagInfo(null);
    setConfidence(DEFAULT_CONFIDENCE);
  };

  return (
    <Modal
      title={groupName}
      open={visible}
      destroyOnClose
      onOk={() => {
        contentRef.current?.form.validateFields().then(() => {
          const _confidence = processConfidenceNumber(
            contentRef.current?.form.getFieldValue(['confidence']),
          );
          selectGroupTag({
            confidence: _confidence,
            extend_crowdId: crowdId,
            groupId,
            dimId: dimId ?? propsGroupTagInfo.dimId,
            groupTagInfo: groupTagInfo ?? propsGroupTagInfo,
            ...groupTagInfo,
            ...propsGroupTagInfo,
          });
          handleClearInfo();
          message.success('标签添加成功');
        });
      }}
      onCancel={handleClearInfo}
    >
      <div style={{ marginBottom: '10px' }}>{description}</div>
      <CrowdCountAdjust
        ref={contentRef}
        minCoverage={minCoverage !== undefined ? minCoverage : '(未知)'}
        maxCoverage={coverage}
        crowd_id={crowdId}
        onRequest={onRequest}
        onSuccess={onSuccess}
        onConfidenceChange={setConfidence}
        value={value}
      />
      <div style={{ marginTop: '30px' }}>
        <h3>当前标签详情 </h3>
        <p style={{ marginBottom: '5px' }}>
          {`当前的使用数据日期为: ${data.p_date || '-'}`}{' '}
        </p>
        <div style={{ display: 'flex' }}>
          <Space size={5} style={{ marginRight: '20px' }}>
            覆盖人数：
            <Spin spinning={loading}>
              {numberWithThousands(data.coverage) ?? '-'}
            </Spin>
            人
          </Space>
          <div>置信度：{confidence.toFixed(2) ?? '-'}</div>
        </div>
      </div>
    </Modal>
  );
};

export default CrowdExpandAdjustModal;
